package com.ithema.reggie.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ithema.reggie.common.Page;
import com.ithema.reggie.common.R;
import com.ithema.reggie.entity.Category;
import com.ithema.reggie.entity.Dish;
import com.ithema.reggie.entity.Setmeal;
import com.ithema.reggie.exception.BusinessException;
import com.ithema.reggie.mapper.CategoryMapper;
import com.ithema.reggie.mapper.DishMapper;
import com.ithema.reggie.mapper.SetMealMapper;
import com.ithema.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    CategoryMapper categoryMapper;

    @Autowired
    DishMapper dishMapper;

    @Autowired
    SetMealMapper setMealMapper;

    @Override
    public R findByPage(Integer pageNum, Integer pageSize) {
        //1.设置分页参数
        PageHelper.startPage(pageNum,pageSize);

        //2.查询列表
        List<Category> list = categoryMapper.findAll();

        //3.用pageInfo封装列表
        PageInfo<Category> pageInfo = new PageInfo<>(list);

        //4.封装返回值page
        Page<Category> page = new Page<>(pageInfo.getList(), pageInfo.getTotal());

        return R.success(page);
    }

    @Override
    public R save(Category category) {

        //封装俩时间
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(category.getCreateTime());

        //调用mapper完成保存
        categoryMapper.save(category);
        return R.success(null);
    }

    /**
     * 作用：修改类别
     * @param category
     * @return
     */
    @Override
    public R update(Category category) {

        //封装更新时间
        category.setUpdateTime(LocalDateTime.now());

        //调用mapper完成更新
        categoryMapper.update(category);

        return R.success(null);
    }

    /**
     * 作用：根据id删除分类
     *
     * @param id
     */
    @Override
    public void removeById(Long id) {
        //1.判断分类下有无菜品,若有抛异常(不能删除)
        List<Dish> dishList = dishMapper.findByCategoryId(id);

        //if (dishList!=null && dishList.size()>0) {}
        if (CollUtil.isNotEmpty(dishList)) {
            throw new BusinessException("该分类下有菜品,不能删除~");
        }

        //2.判断分类下有无套餐,若有抛异常(不能删除)
        List<Setmeal> setmealList = setMealMapper.findByCategoryId(id);
        if (CollUtil.isNotEmpty(setmealList)) {
            throw new BusinessException("该分类下有套餐,不能删除~");
        }

        //调用mapper完成删除
        categoryMapper.deleteById(id);
    }

    /**
     * 根据type查询类别列表
     * @param type
     * @return
     */
    @Override
    public R findAllByType(Integer type) {
        List<Category> list = categoryMapper.findAllByType(type);
        return R.success(list);
    }
}
